<?php

namespace App\Http\Controllers\Api;

use App\Models\Role;
use Illuminate\Http\Request;

class PermissionController extends BaseController
{
    /**
     * 获取所有权限列表
     */
    public function index(Request $request)
    {
        try {
            // 从所有角色中收集权限
            $roles = Role::where('status', 'active')->get();
            $permissions = [];

            foreach ($roles as $role) {
                if ($role->permissions) {
                    foreach ($role->permissions as $permission) {
                        if (!isset($permissions[$permission])) {
                            $permissions[$permission] = [
                                'code' => $permission,
                                'name' => $this->getPermissionName($permission),
                                'description' => $this->getPermissionDescription($permission),
                                'module' => $this->getPermissionModule($permission),
                                'roles' => []
                            ];
                        }

                        if (!in_array($role->name, $permissions[$permission]['roles'])) {
                            $permissions[$permission]['roles'][] = $role->name;
                        }
                    }
                }
            }

            // 转换为数组格式
            $permissions = array_values($permissions);

            return $this->success($permissions, '获取权限列表成功');
        } catch (\Exception $e) {
            return $this->error('获取权限列表失败：' . $e->getMessage());
        }
    }

    /**
     * 获取权限详情
     */
    public function show($permissionCode)
    {
        try {
            $roles = Role::where('status', 'active')
                ->whereJsonContains('permissions', $permissionCode)
                ->get(['id', 'name', 'code']);

            $permission = [
                'code' => $permissionCode,
                'name' => $this->getPermissionName($permissionCode),
                'description' => $this->getPermissionDescription($permissionCode),
                'module' => $this->getPermissionModule($permissionCode),
                'roles' => $roles->map(function ($role) {
                    return [
                        'id' => $role->id,
                        'name' => $role->name,
                        'code' => $role->code
                    ];
                })
            ];

            return $this->success($permission, '获取权限详情成功');
        } catch (\Exception $e) {
            return $this->error('获取权限详情失败：' . $e->getMessage());
        }
    }

    /**
     * 获取当前用户权限
     */
    public function userPermissions(Request $request)
    {
        try {
            $user = $this->getCurrentUser();

            if (!$user) {
                return $this->error('用户未登录', 401);
            }

            $permissions = $this->getUserPermissions($user);

            return $this->success($permissions, '获取用户权限成功');
        } catch (\Exception $e) {
            return $this->error('获取用户权限失败：' . $e->getMessage());
        }
    }

    /**
     * 检查用户权限
     */
    public function checkUserPermission(Request $request)
    {
        try {
            $data = $this->validateRequest($request, [
                'permission' => 'required|string'
            ]);

            $user = $this->getCurrentUser();

            if (!$user) {
                return $this->error('用户未登录', 401);
            }

            $hasPermission = $user->hasPermission($data['permission']);

            return $this->success([
                'permission' => $data['permission'],
                'has_permission' => $hasPermission
            ], '权限检查完成');
        } catch (\Exception $e) {
            return $this->error('权限检查失败：' . $e->getMessage());
        }
    }

    /**
     * 获取权限模块分组
     */
    public function getModules(Request $request)
    {
        try {
            $modules = [
                'system' => [
                    'name' => '系统管理',
                    'permissions' => [
                        'system.manage',
                        'system.settings',
                        'system.backup',
                        'system.logs'
                    ]
                ],
                'user' => [
                    'name' => '用户管理',
                    'permissions' => [
                        'user.manage',
                        'user.view',
                        'user.create',
                        'user.edit',
                        'user.delete'
                    ]
                ],
                'role' => [
                    'name' => '角色管理',
                    'permissions' => [
                        'role.manage',
                        'role.view',
                        'role.create',
                        'role.edit',
                        'role.delete',
                        'role.assign'
                    ]
                ],
                'hr' => [
                    'name' => '人事管理',
                    'permissions' => [
                        'hr.manage',
                        'employee.manage',
                        'employee.view',
                        'employee.create',
                        'employee.edit',
                        'employee.delete',
                        'department.manage',
                        'department.view',
                        'department.create',
                        'department.edit',
                        'department.delete',
                        'position.manage',
                        'position.view',
                        'position.create',
                        'position.edit',
                        'position.delete'
                    ]
                ]
            ];

            return $this->success($modules, '获取权限模块成功');
        } catch (\Exception $e) {
            return $this->error('获取权限模块失败：' . $e->getMessage());
        }
    }

    /**
     * 获取用户权限列表（私有方法）
     */
    private function getUserPermissions($user)
    {
        $permissions = [];

        // 检查用户是否为超级管理员
        if ($user->hasRole('super_admin')) {
            return ['*'];
        }

        // 从用户的角色中收集权限
        foreach ($user->roles as $role) {
            if ($role->isActive() && $role->permissions) {
                $permissions = array_merge($permissions, $role->permissions);
            }
        }

        return array_unique($permissions);
    }

    /**
     * 获取权限名称
     */
    private function getPermissionName($permission)
    {
        $permissionNames = [
            // 系统权限
            'system.manage' => '系统管理',
            'system.settings' => '系统设置',
            'system.backup' => '系统备份',
            'system.logs' => '系统日志',

            // 用户权限
            'user.manage' => '用户管理',
            'user.view' => '查看用户',
            'user.create' => '创建用户',
            'user.edit' => '编辑用户',
            'user.delete' => '删除用户',

            // 角色权限
            'role.manage' => '角色管理',
            'role.view' => '查看角色',
            'role.create' => '创建角色',
            'role.edit' => '编辑角色',
            'role.delete' => '删除角色',
            'role.assign' => '分配角色',

            // 人事权限
            'hr.manage' => '人事管理',
            'employee.manage' => '员工管理',
            'employee.view' => '查看员工',
            'employee.create' => '创建员工',
            'employee.edit' => '编辑员工',
            'employee.delete' => '删除员工',
            'department.manage' => '部门管理',
            'department.view' => '查看部门',
            'department.create' => '创建部门',
            'department.edit' => '编辑部门',
            'department.delete' => '删除部门',
            'position.manage' => '岗位管理',
            'position.view' => '查看岗位',
            'position.create' => '创建岗位',
            'position.edit' => '编辑岗位',
            'position.delete' => '删除岗位',
        ];

        return $permissionNames[$permission] ?? $permission;
    }

    /**
     * 获取权限描述
     */
    private function getPermissionDescription($permission)
    {
        $permissionDescriptions = [
            'system.manage' => '管理系统基本设置和配置',
            'user.manage' => '管理系统的所有用户账户',
            'role.manage' => '管理系统角色和权限分配',
            'hr.manage' => '管理人事相关信息和流程',
            'employee.manage' => '管理员工基本信息和档案',
            'department.manage' => '管理组织架构和部门设置',
            'position.manage' => '管理岗位信息和职位设置',
        ];

        return $permissionDescriptions[$permission] ?? '';
    }

    /**
     * 获取权限所属模块
     */
    private function getPermissionModule($permission)
    {
        $moduleMap = [
            'system' => ['system.manage', 'system.settings', 'system.backup', 'system.logs'],
            'user' => ['user.manage', 'user.view', 'user.create', 'user.edit', 'user.delete'],
            'role' => ['role.manage', 'role.view', 'role.create', 'role.edit', 'role.delete', 'role.assign'],
            'hr' => ['hr.manage', 'employee.manage', 'employee.view', 'employee.create', 'employee.edit', 'employee.delete', 'department.manage', 'department.view', 'department.create', 'department.edit', 'department.delete', 'position.manage', 'position.view', 'position.create', 'position.edit', 'position.delete']
        ];

        foreach ($moduleMap as $module => $permissions) {
            if (in_array($permission, $permissions)) {
                return $module;
            }
        }

        return 'other';
    }
}
